<?php
/**
 * File
 *
 * @package scorpion-magenta
 * @author Nicky van Meurs
 * @copyright 2012
 * @version 1.0
 * @access public
 */
class File
{
	/**
	 * @var string
	 */
	protected $_filePath = null;

	/**
	 * @param string $filePath
	 */
	public function __construct($filePath=null)
	{
		$this->_filePath = $filePath;
	}

	/**
	 * Set path to file
	 * @param string $filePath
	 * @return string
	 */
	public function setFilePath($filePath)
	{
		$this->_filePath = $filePath;
		return $this->_filePath;
	}

	/**
	 * Get path to file
	 * @return string
	 */
	public function getFilePath()
	{
		return $this->_filePath;
	}

	/**
	 * Read a file
	 * @return string
	 */
	public function readFile()
	{
		return file_get_contents($this->_filePath);
	}

	/**
	 * Overwrite a file
	 * @param string $content
	 * @return bool
	 */
	public function overwriteFile($content)
	{
		$f = fopen($this->_filePath, 'w');
		fwrite($f, $content . PHP_EOL);
		return fclose($f);
	}

	/**
	 * Add a new line to a file
	 * @param string $content
	 * @return bool
	 */
	public function appendFile($content)
	{
		$f = fopen($this->_filePath, 'a');
		fwrite($f, $content . PHP_EOL);
		return fclose($f);
	}

	/**
	 * List all files in given directory
	 * @param string $dir
	 * @return array
	 */
	public function listFilesInDir($dir)
	{
		$dirHandle = opendir($dir);
		$fileList = array();

		while(false !== ($entry = readdir($dirHandle)))
			if ($entry != '.' && $entry != '..')
				$fileList[] = $entry;

		closedir($dirHandle);
		return $fileList;
	}

	/**
	 * Check if file exists
	 * @return bool
	 */
	public function fileExists()
	{
		return file_exists($this->_filePath)? true : false;
	}

	/**
	 * Check if file is empty
	 * @return string
	 */
	public function fileIsEmpty()
	{
		return (filesize($this->_filePath) == 0)? true : false;
	}

	/**
	 * Split file content into lines
	 * @return array
	 */
	public function getFileLines()
	{
		return explode(PHP_EOL, $this->readFile());
	}

	/**
	 * Empty the file's content
	 * @return bool
	 */
	public function emptyFile()
	{
		return file_put_contents($this->_filePath, '');
	}
}
?>